﻿using System;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Linq;

namespace AsynchronousMethods
{
  public class Client
  {
    public static void Test (bool slow, string hostName, int port)
    {
      byte [] toSend = new byte [Program.MessageLength];
      byte [] reply = new byte [Program.MessageLength];

      // Make up a message of random bytes. We're not worried about genuine randomness here.
      new Random ().NextBytes (toSend);

      using (TcpClient client = new TcpClient (hostName, port))
      using (Stream s = client.GetStream ())
      {
        int mid = toSend.Length / 2;
        s.Write (toSend, 0, mid);             // Send first half of message

        if (slow) Thread.Sleep (5000);        // Wait 5 seconds if we're a slow client

        s.Write (toSend, mid, toSend.Length - mid);   // Second second half of message

        int bytesRead = 0, chunkSize = 1;                    // Read reply from server
        while (bytesRead < reply.Length && chunkSize > 0)
          bytesRead +=
            chunkSize = s.Read (reply, bytesRead, reply.Length - bytesRead);
      }

      // Check that we've got a valid message back. All the bytes should be reversed.

      for (int i = 0; i < Program.MessageLength; i++)
        if (toSend [i] != reply [Program.MessageLength - i - 1])
          throw new Exception ("Invalid reply at index " + i);

      Console.Write (slow ? "S" : "F");       // Report that we've finished
    }
  }
}
